import utils from '../../../utils/util';
import { OrderStatus } from '../config';
import { OrderDetail, OrderFile, CancelOrder, ConfirmPay, ConfirmReceipt } from '../../../services/order/order';

Page({
  data: {
    pageLoading: true,
    orderInfo: {}, // 订单信息
    goodsList: [], // 订单商品
    logisticsNodes: [],   // 物流
    backRefresh: false, // 用于接收其他页面back时的状态
    fileVisible: false,   // 订单附件
    fileList: [],
    OrderStatus,   // 订单状态
  },

  onLoad(query) {
    this.orderId = query.orderId;
    this.init();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  // 页面初始化，会展示pageLoading
  init() {
    this.setData({ pageLoading: true });
    this.getDetail()
  },

  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const { callback } = e.detail;
    return this.getDetail().then(() => callback && callback());
  },

  getDetail() {
    const params = { orderId: this.orderId, };
    this.setData({ pageLoading: true });
    OrderDetail(params).then(res => {
      this.setData({ pageLoading: false });
      if (res.code === '0000') {
        let logisticsNodes = []
        if (res.data.LogisticsInfo && res.data.LogisticsInfo.deliveryContentList.length != 0) logisticsNodes = res.data.LogisticsInfo.deliveryContentList.reverse();
        this.setData({ orderInfo: Object.assign(res.data.orderInfo, res.data.LogisticsInfo), goodsList: res.data.orderGoodsList, logisticsNodes })
      }
    })
  },

  /* 订单按钮操作 */
  onOrderBtnTap(event) {
    let { order, type } = event.target.dataset, that = this;
    switch (type) {
      case 'takeDelivery':
        wx.showModal({
          title: "",
          content: "是否确认收货",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              ConfirmReceipt({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  utils.showToast('操作成功');
                  that.getDetail()
                }
              })
            }
          }
        });
        break;
      case 'payment':
        wx.showModal({
          title: "",
          content: "是否确认支付",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              ConfirmPay({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  utils.showToast('操作成功');
                  that.getDetail()
                }
              })
            }
          }
        });
        break;
      case 'cancel':
        wx.showModal({
          title: "",
          content: "是否确认取消订单",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              CancelOrder({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  utils.showToast('操作成功');
                  that.getDetail()
                }
              })
            }
          }
        });
        break;
      default:
        break;
    }
  },

  /* 商品详情 */
  onGoodsCardTap(e) {
    const { index } = e.currentTarget.dataset;
    const goods = this.data.orderInfo.orderItemVOs[index];
    wx.navigateTo({ url: `/pages/goods/details/index?spuId=${goods.spuId}` });
  },

  /* 复制订单号 */
  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.orderInfo.orderNo,
    });
  },

  /* 物流详情 */
  onDeliveryClick() {
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?orderId=${this.data.orderInfo.id}`,
    });
  },

  /* 订单附件 */
  onTapFile(e) {
    const { type } = e.currentTarget.dataset;
    OrderFile({ orderId: this.orderId, type }).then(res => {
      if (res.code === '0000') {
        let fileList = [];
        if (res.data) {
          res.data.fileList.forEach(item => {
            let type = utils.getFileType(item)
            fileList.push({ type, url: item, iconName: `file-${type}` })
          });
          this.setData({ fileVisible: true, fileList })
        } else {
          utils.showToast('文件未上传,请稍后再查看', 'none');
        }
      }
    })
  },
  ClosefileVisible() {
    this.setData({ fileVisible: false })
  },
});
